package cn.hxh.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/8/19 22:29
 */

@WebServlet("/images")
public class ImagesServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //如何让浏览器5秒后刷新
        resp.setHeader("refresh","3");
        //在内存中生成图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //得到图片
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        //设置图片背景颜色
        graphics.setColor(Color.black);
        graphics.fillRect(0,0,80,20);
        //给图片写数据
        graphics.setColor(Color.white);
        graphics.setFont(new Font(null,Font.BOLD,20));
        graphics.drawString(getRandom(),0,20);
        resp.setContentType("image/jpeg");
        //网站缓存关闭
        resp.setDateHeader("expires",-1);
        resp.setHeader("Cache-Control","no-cache");
        ImageIO.write(image,"jpg",resp.getOutputStream());






    }
    public static String getRandom(){
        Random random = new Random();
        String s = random.nextInt(99999)+"";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 7; i++){
            buffer.append(s);
        }
        String str = buffer.toString().substring(0, 4);
        return str;
    }


}
